'use strict';

var Imap = require('imap');
var check = {
    EmailChecker: function(opts) {
        var _userConfig = {
            user: opts.user,
            password: opts.pass,
            host: opts.host,
            port: opts.port
        };
        var _persencod = 1000*60*60;
        var _unreads = [];

        var _fetchDone;
        /**
         * 拉取未读邮件
         * @return {[type]} [description]
         */
        var _getUnseen = function(imap) {
            _unreads = [];
            imap.openBox('INBOX', true, function(err, mailBox) {
                if (err) {
                    throw err;
                }

                imap.search(['UNSEEN'], function(err, results) {
                    if (results.length > 0) {
                        var f = imap.fetch(results, {
                            bodies: 'HEADER.FIELDS (FROM TO SUBJECT DATE)',
                            struct: true
                        });
                        f.on('message', function(msg, seqno) {
                            var prefix = '(#' + seqno + ') ';
                            msg.on('body', function(stream, info) {
                                var buffer = '';
                                stream.on('data', function(chunk) {
                                    buffer += chunk.toString('utf8');
                                });
                                stream.once('end', function() {
                                    // console.log(prefix + 'Parsed header: %s', inspect(Imap.parseHeader(buffer)));
                                    var mail = Imap.parseHeader(buffer);
                                    _unreads.push(mail);
                                });
                            })
                            // msg.once('end', function() {
                                // console.log(prefix + 'Finished');
                            // });
                        });
                        f.once('end', function() {
                            //拉取结束，等待时机后重新开始
                            _fetchDone(_unreads);
                            setTimeout(function() {
                                _getUnseen(imap);
                            }, _persencod);
                        });
                    }
                });
            });

        };

        var check = {
        	setMailDoneListener:function(fn){
        		_fetchDone=fn;
        		return this;
        	},
            go: function() {
                //创建imap对象
                var imap = new Imap({
                    user: _userConfig.user,
                    password: _userConfig.password,
                    host: _userConfig.host,
                    port: _userConfig.port,
                    tls: true
                });

                imap.on('ready', function() {
                    _getUnseen(imap);
                });
                imap.connect();
                return this;
            }
        };
        return check;
    }
}

module.exports = check;
